<template>
  <basic-container>
    <div class="container-body">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-row>
          <el-form-item label="项目编号:" label-width="82px">
            <el-input v-model="query.projectCode" clearable placeholder="项目编号" size="small"></el-input>
          </el-form-item>
          <el-form-item label="审计类型:" label-width="82px">
            <el-select v-model="query.auditType" clearable>
              <el-option v-for="dict in dict.type.audit_type" v-if="dict.value !== '0'" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度:" label-width="110px">
            <el-select v-model="query.noticeYear" clearable>
              <el-option v-for="planHeadYear in planHeadYears" :key="planHeadYear" :label="planHeadYear" :value="planHeadYear"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="项目名称:" label-width="82px">
            <el-input v-model="query.projectName" clearable placeholder="项目名称" size="small"></el-input>
          </el-form-item>
          <el-form-item label="审批状态:" label-width="82px">
            <el-select v-model="query.auditStatus" clearable>
              <el-option v-for="dict in dict.type.audit_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资料提交状态:" label-width="110px">
            <el-select v-model="query.submitStatus" clearable>
              <el-option label="待发送" :value="0"></el-option>
              <el-option label="待提交" :value="1"></el-option>
              <el-option label="已提交，待确认" :value="2"></el-option>
              <el-option label="退回，待提交" :value="3"></el-option>
              <el-option label="已确认" :value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button :loading="loading" icon="el-icon-search" size="small" type="primary" @click="onSearch">搜索
            </el-button>
            <el-button :loading="loading" icon="el-icon-delete" size="small" @click="searchReset">清空</el-button>
          </el-form-item>
        </el-row>
      </el-form>
<!--      <div class="btn-operate">-->
<!--        <el-button icon="el-icon-plus" size="small" type="primary" @click="addOrUpdateHandle()">-->
<!--          审计通知书-->
<!--        </el-button>-->
<!--      </div>-->
      <el-table v-loading="loading" :data="data" border
                header-row-class-name="container-table-header"
                highlight-current-row @cell-click="handleCellClick"
                row-key="id" size="small" stripe style="width: 100%;margin-bottom: 20px;">
        <el-table-column label="年度" prop="noticeYear" width="80">
        </el-table-column>
        <el-table-column label="项目编号" prop="projectCode">
        </el-table-column>
        <el-table-column label="项目名称" prop="projectName">
        </el-table-column>
        <el-table-column label="通知书文号" prop="documentNumber">
        </el-table-column>
        <el-table-column label="审计类型" prop="effectiveDate" >
          <template slot-scope="scope">
            <DictTag :options="dict.type.audit_type" :value="scope.row.auditType"></DictTag>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" prop="auditStatus" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.auditStatus | auditStatusTag">{{ scope.row.auditStatus | auditStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资料提交状态" prop="submitStatus" width="150">
          <template slot-scope="scope">
            <el-tag :type="scope.row.submitStatus | submitStatusTag">{{ scope.row.submitStatus | submitStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="255">
          <template slot-scope="scope">
            <el-button v-if="permissions.project_notice_get" icon="el-icon-view" size="small" type="text" @click="showViewBox(scope.row)">查看</el-button>
            <el-button v-if="permissions.project_notice_add && (scope.row.auditStatus === 0 || scope.row.auditStatus === 2)" icon="el-icon-edit" size="small" type="text" @click="addOrUpdateHandle(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.taskId" type="text" size="small" icon="el-icon-edit" @click="showTaskAuditTaskDialog(scope.row)">审批</el-button>
            <el-button v-if="scope.row.auditStatus > 0" type="text" size="small" icon="el-icon-view" @click="showTaskAuditLogDialog(scope.row)">审批日志</el-button>
            <el-button v-if="permissions.project_notice_upload && (scope.row.submitStatus === 1 || scope.row.submitStatus === 3)"
                       icon="el-icon-edit" size="small" type="text" @click="showAttachmentViewBox(scope.row)">上传资料</el-button>
            <el-button v-if="permissions.project_notice_upload_audit && (scope.row.submitStatus === 2)"
                       icon="el-icon-edit" size="small" type="text" @click="showAttachmentAuditBox(scope.row)">审核资料</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="container-page">
        <el-pagination
          :current-page="page.current"
          :page-size="10"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChange"
          @current-change="currentChange">
        </el-pagination>
      </div>
    </div>

    <el-dialog top="5vh" :title="formTitle" :visible.sync="viewBox"
               :append-to-body="true" :before-close="closeViewBox" width="1200px">
      <ProjectNoticeAuditView :params="form"></ProjectNoticeAuditView>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeViewBox" size="small" icon="el-icon-close">关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog top="5vh" title="上传资料" :visible.sync="attachmentViewBox"
               :append-to-body="true" :before-close="closeAttachmentViewBox" width="1200px">
      <div class="ledgerTitle">基本信息</div>
      <component :is="auditView" :params="form"></component>
      <el-row>
        <el-col>
          <div class="ledgerTitle">资料清单</div>
          <el-table
            :data="tableData"
            :model="tableData"
            style="width: 100%"
            max-height="450"
            highlight-current-row
          >
            <el-table-column label="序号" width="100">
              <template #default="{ $index }">
                <span>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="必传" width="100">
              <template #default="{ row }">
                <el-tag :type="row.required | tureOrFalseTag2">{{ row.required | tureOrFalse }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="纸质文件" width="180" align="center">
              <template #default="{ row }">
                <el-radio-group v-model="row.paperBased">
                  <el-radio border style="margin: 0 5px 0 5px" :label="1">是</el-radio>
                  <el-radio border style="margin: 0 5px 0 5px" :label="0">否</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="资料名称" width="280">
              <template #default="{ row }">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column label="份数" width="50">
              <template #default="{ row }">
                {{ row.copies }}
              </template>
            </el-table-column>
            <el-table-column label="被审计单位上传资料">
              <template #default="{ row, $index }">
                <el-upload v-if="row.paperBased === 0"
                  class="upload-demo"
                  ref="upload"
                  action="/admin/sys-file/upload"
                  :headers="{Authorization}"
                  :on-success="(e) => handleSuccess(e, $index)"
                  :on-preview="handlePreview"
                  :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                  :show-file-list="true"
                  :file-list="row.fileList">
                  <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="{ row }">
                <el-input v-model="row.remark" :autosize="{ minRows: 1}" type="textarea" placeholder="输入备注"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="form.comment">
            <div class="ledgerTitle">退回原因</div>
            <div style="margin-left: 21px">{{form.comment}}</div>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAttachmentViewBox" size="small" icon="el-icon-close">关闭</el-button>
        <el-button type="primary" @click="saveAttachments" size="small" icon="el-icon-check">保存</el-button>
        <el-button type="primary" @click="submitAttachments" size="small" icon="el-icon-check">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog top="5vh" title="审核资料" :visible.sync="attachmentAuditBox"
               :append-to-body="true" :before-close="closeAttachmentAuditBox" width="1200px">
      <div class="ledgerTitle">基本信息</div>
      <component :is="auditView" :params="form"></component>
      <el-row>
        <el-col>
          <div class="ledgerTitle">资料清单</div>
          <el-table
            :data="tableData"
            :model="tableData"
            style="width: 100%"
            max-height="450"
            highlight-current-row
          >
            <el-table-column label="序号" width="100">
              <template #default="{ $index }">
                <span>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="必传" width="100">
              <template #default="{ row }">
                <el-tag :type="row.required | tureOrFalseTag2">{{ row.required | tureOrFalse }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="纸质文件" width="100">
              <template #default="{ row }">
                <el-tag :type="row.paperBased | tureOrFalseTag2">{{ row.paperBased | tureOrFalse }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="资料名称" width="280">
              <template #default="{ row }">
                {{ row.name }}
              </template>
            </el-table-column>
            <el-table-column label="份数" width="50">
              <template #default="{ row }">
                {{ row.copies }}
              </template>
            </el-table-column>
            <el-table-column label="被审计单位上传资料">
              <template #default="{ row, $index }">
                <el-upload v-if="row.paperBased === 0"
                  class="upload-demo"
                  ref="upload"
                  action="/admin/sys-file/upload"
                  :headers="{Authorization}"
                  :on-success="(e) => handleSuccess(e, $index)"
                  :on-preview="handlePreview"
                  :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                  :show-file-list="true"
                  :file-list="row.fileList">
                  <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="{ row }">
                {{row.remark}}
              </template>
            </el-table-column>
          </el-table>
          <div>
            <div class="ledgerTitle">退回原因</div>
            <el-input v-model="form.comment" :autosize="{ minRows: 4}" type="textarea"></el-input>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAttachmentAuditBox" size="small" icon="el-icon-close">关闭</el-button>
        <el-button type="danger" @click="handleAudit(false)" size="small" icon="el-icon-close" :loading="loading">退回</el-button>
        <el-button type="success" @click="handleAudit(true)" size="small" icon="el-icon-check" :loading="loading">确认</el-button>
      </span>
    </el-dialog>

    <table-form ref="addOrUpdate" @cancelDialog="closeNoticeDialog"></table-form>
    <TaskAuditDialog :dialog="taskAuditDialog" @setValue="setTaskAuditTaskDialog" @closeDialog="closeTaskAuditTaskDialog" ref="taskAuditDialog" />
    <TaskAuditLogDialog :dialog="taskAuditLogDialog" :process-id="processId" @closeDialog="closeTaskAuditTaskLogDialog"/>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import {
  fetchList,
  getNotice,
  saveAttachments,
  submitAttachments,
  auditSubmit
} from "@/api/adis/project/notice";
import TableForm from "@/components/form/noticeForm";
import TaskAuditDialog from "@/components/act/TaskAuditDialog";
import TaskAuditLogDialog from "@/components/act/TaskAuditLogDialog";
import ProjectNoticeAuditView from "@/components/actForm/ProjectNoticeAuditView";
import {listPlanHeadYear} from "@/api/adis/work/plan";
import Template from "@/views/adis/base/template.vue";

export default {
  components: {
    Template,
    TableForm,
    TaskAuditDialog,
    TaskAuditLogDialog,
    ProjectNoticeAuditView,
  },
  dictTypes: ['audit_type','audit_status'],
  data() {
    return {
      loading: false,
      formTitle: '',
      viewBox: false,
      attachmentViewBox: false,
      attachmentAuditBox: false,
      processId : '',
      taskAuditDialog: false,
      taskAuditLogDialog: false,
      query: {},
      form: {
        comment: ''
      },
      tableData: [],
      page: {
        size: 10,
        current: 1,
        total: 0
      },
      data: [],
      planHeadYears: [],
      Authorization: '',
      auditView: '',
    }
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"]),
  },
  created() {
    this.onLoad(this.page);
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    // 获取所有已经审批通过的年度计划年度
    listPlanHeadYear(){
      listPlanHeadYear().then((res) => {
        this.$set(this,"planHeadYears", res.data.data)
      });
    },

    handleCellClick(row, column) {
      if (row && column.label !== "操作"){
        this.showViewBox(row)
      }
    },

    // 新增 / 修改
    addOrUpdateHandle (row, type) {
      const Edit = row ? row : {compilerId: this.userInfo.userId, compiler: this.userInfo.realname}
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(Edit, type)
      })
    },
    closeNoticeDialog() {
      this.onLoad(this.page);
    },
    onSearch() {
      this.page.current = 1;
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.current = 1;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.isEngineering = false
      this.query.isTermination = false;
      fetchList(Object.assign(params, this.query, page)).then(res => {
        this.loading = false;
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.data.forEach(record => {
          record.documentNumber = '浙工大审通（'+ record.noticeYear +'）'+ record.noticeCode +'号';
        });
        this.listPlanHeadYear()
      }, () => {
        this.loading = false;
      });
    },

    // 表单提交
    submitAttachments() {
      let count = 0
      try{
        this.tableData.forEach((item, i) => {
          if(item.name === ''){
            this.$message({
              type: "warning",
              message: '第' + (i + 1) + "行资料名称不能为空"
            });
            count++
            throw Error();
          }
          // 只有当用户部门为被审计单位、当前项不是必传项、不是纸质文件时，才进行附件验证
          if(this.userInfo.userId === this.form.auditedCompanyId && item.required === 1 && item.paperBased !== 1) {
            if (!item.fileList || item.fileList.length === 0) {
              this.$message({
                type: "warning",
                message: '第' + (i + 1) + "行资料附件不能为空"
              });
              count++
              throw Error();
            }
          }
        })
      }catch(e){
        console.log(e)
      }
      if (count > 0) return
      this.form.noticeAttachments = []
      this.tableData.forEach((item, i) => {
        item.attachments = []
        if (item.fileList){
          item.fileList.forEach(file => {
            item.attachments.push({fileName: file.name, fileUrl: file.url})
          })
        }
        this.form.noticeAttachments.push(item)
      })
      this.loading = true;
      submitAttachments(this.form).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.closeAttachmentViewBox();
        this.onLoad(this.page);
      }, () => {
        this.loading = false;
      });
    },

    handleAudit(result) {
      this.loading = true;
      auditSubmit({noticeId: this.form.noticeId, result: result, comment: this.form.comment}).then(() => {
        this.$message({
          type:"success",
          message: "操作成功!"
        });
        this.closeAttachmentAuditBox();
        this.onLoad(this.page);
      });
    },

    saveAttachments() {
      this.form.noticeAttachments = []
      this.tableData.forEach((item, i) => {
        item.attachments = []
        item.fileList.forEach(file => {
          item.attachments.push({fileName: file.name, fileUrl: file.url})
        })
        this.form.noticeAttachments.push(item)
      })
      this.loading = true;
      saveAttachments(this.form).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.closeAttachmentViewBox();
        this.onLoad(this.page);
      }, () => {
        this.loading = false;
      });
    },

    currentChange(current) {
      this.page.current = current;
      this.onLoad(this.page);
    },
    sizeChange(size) {
      this.page.size = size;
      this.onLoad(this.page);
    },

    showViewBox(row) {
      getNotice(row.noticeId).then(noticeResponse => {
        this.form = noticeResponse.data.data
        this.formTitle = row.projectName;
        this.viewBox = true;
      })
    },
    closeViewBox() {
      this.viewBox = false;
    },

    showAttachmentViewBox(row) {
      getNotice(row.noticeId).then((noticeResponse) => {
        this.form = noticeResponse.data.data;
        this.form.releaseTime = this.form.updateTime.split(" ")[0]
        this.auditView = 'NoticeAuditTypeAuditView'+ this.form.auditType
        this.tableData = noticeResponse.data.data.noticeAttachments || []
        this.tableData.forEach(item => {
          item.fileList = []
          item.attachments.forEach(col => {
            item.fileList.push({name: col.fileName, url: col.fileUrl})
          })
        })
        this.attachmentViewBox = true;
      })
    },
    closeAttachmentViewBox() {
      this.attachmentViewBox = false;
    },

    showAttachmentAuditBox(row) {
      getNotice(row.noticeId).then((noticeResponse) => {
        this.form = noticeResponse.data.data;
        this.form.releaseTime = this.form.updateTime.split(" ")[0]
        this.auditView = 'NoticeAuditTypeAuditView'+ this.form.auditType
        this.tableData = noticeResponse.data.data.noticeAttachments || []
        this.tableData.forEach(item => {
          item.fileList = []
          item.attachments.forEach(col => {
            item.fileList.push({name: col.fileName, url: col.fileUrl})
          })
        })
        this.attachmentAuditBox = true;
      })
    },
    closeAttachmentAuditBox() {
      this.attachmentAuditBox = false;
    },

    // -- 资料上传
    handleRemove(file, fileList, i) {
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    handleSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
      }
    },

    /**=========审批相关==begin===========*/
    showTaskAuditTaskDialog(row) {
      this.taskAuditDialog = true;
      this.$refs['taskAuditDialog'].initData({taskId: row.taskId, processId: row.processId});
    },
    closeTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
    },
    setTaskAuditTaskDialog() {
      this.taskAuditDialog = false;
      this.onLoad(this.page);
    },
    showTaskAuditLogDialog(row) {
      this.processId = row.processId;
      this.taskAuditLogDialog = true;
    },
    closeTaskAuditTaskLogDialog() {
      this.taskAuditLogDialog = false;
    },
    /**=========审批相关==end===========*/
  }
}
</script>

<style>
.colums {
  display: flex;
  height: calc(100vh - 104px);
}

.colums_left {
  flex: 1 1;
  display: flex;
  flex-direction: column;
}

.colums_left_top {
  font-size: 13px;
  color: #222222;
}

.colums_left_middle {
  flex: 1 1;
  width: calc(100% - 10px);
  background-color: #ffffff;
  position: relative;
}

.middleForm {
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  padding: 30px 0;
  overflow: scroll;
}

.middleForm .el-dialog__body {
  padding: 10px 20px 80px;
}

.colums_left_middle .leftIcon {
  position: absolute;
  top: calc((100% - 100px) / 2);
  right: -10px;
  background: #cccccc;
  border-radius: 3px;
  width: 10px;
  height: 100px;
  font-size: 12px;
  color: #ffffff;
  font-weight: bolder;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.colums_left_bot {
  font-size: 14px;
  padding-top: 10px;
  padding: 10px 150px 0;
}

.botIcon {
  color: #409EFF;
  font-weight: bolder;
}

.set-form {
  display: flex;
  padding-bottom: 8px;
}

.set-label1 {
  width: 50px;
  margin-right: 10px;
  text-align: right;
  line-height: 28px;
}

.set-label2 {
  width: 90px;
  margin-right: 10px;
  text-align: right;
  line-height: 28px;
}

.colums_right {
  width: 300px;
  background-color: rgb(250, 250, 250);
}

.colums_right_box {
  padding: 0 10px 10px 10px;
  font-size: 12px;
}

.colums_right_box_title {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
}

.colums_right_box_title .link {
  color: #999999;
  font-weight: normal;
  cursor: pointer;
}

.colums_right_box_title .link:hover {
  color: #409EFF;
}

.colums_right .el-tabs__item {
  font-size: 12px;
  padding: 0 10px;
  color: #555555;
}

.colums_right .el-tabs__item.is-active {
  color: #409EFF !important;
}

.colums_right .el-tabs--top .el-tabs__item.is-top:nth-child(2) {
  padding-left: 10px;
}

.colums_right_box .template {
  padding: 5px 15px;
}

.colums_right_box .template li {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  list-style: inside;
}

.colums_right_box_tips {
  color: #999999;
}

.colums_right_box_typeBox {
  display: flex;
  padding-top: 10px;
}

.colums_right_box_typeBox .typeBox {
  width: 33.3%;
  height: 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
  box-shadow: 0px 6px 6px 0px rgba(122, 133, 155, 0.2);
  color: #ffffff;
  margin: 0 5px;
}

.colums_right_box_typeBox .type1 {
  background-color: #2085EC;
}

.colums_right_box_typeBox .type2 {
  background-color: #05CE9D;
}

.colums_right_box_typeBox .type3 {
  background-color: #32BEF2;
}

.colums_right_box_end {
  display: flex;
  padding-top: 15px;
}

.colums_right_box_end .endBox {
  flex: 1 1;
  display: flex;
  position: relative;
}

.colums_right_box_end .endBox .arrow1 {
  z-index: 1;
  position: absolute;
  left: -9px;
  top: 3px;
  width: 0;
  height: 0;
  border-right: 10px solid #E2EAF1;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
}

.colums_right_box_end .endBox .arrow2 {
  z-index: 2;
  position: absolute;
  left: -7px;
  top: 5px;
  width: 0;
  height: 0;
  border-right: 8px solid #ffffff;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
}

.colums_right_box_end .endBox .item_content {
  flex: 1 1;
  position: relative;
  background-color: #fff;
  border: 1px solid #E2EAF1;
  padding: 10px 20px;
}

.colums_right_box_end .el-icon-help {
  margin-right: 10px;
  margin-top: 5px;
  font-size: 18px;
  color: #999999;
}
</style>
